package com.lmk.ms.common.net.tcp.client;

import com.lmk.ms.common.net.tcp.client.service.TcpClientService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * TCP客户端
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2023/4/25
 */
@Slf4j
public class TcpClient {

    /** 服务端IP地址 */
    private String serverHost;

    /** 服务端监听端口 */
    private int serverPort;

    /** 连接超时的时间 */
    private int timeout = 3000;

    private Socket socket = null;

    private InetSocketAddress serverAddress;

    /**
     * 构建客户端实例
     * @param host
     * @param port
     */
    private TcpClient(String host, int port) {
        this.serverHost = host;
        this.serverPort = port;
    }

    /**
     * 构造函数设置超时时间
     * @param host
     * @param port
     * @param timeout
     */
    private TcpClient(String host, int port, int timeout) {
        this(host, port);
        this.timeout = timeout;
    }

    /**
     * 连接服务端
     * @param host
     * @param port
     * @return
     */
    public static TcpClient connect(String host, int port){
        return new TcpClient(host, port);
    }

    /**
     * 连接服务端
     * @param host
     * @param port
     * @param timeout
     * @return
     */
    public static TcpClient connect(String host, int port, int timeout){
        return new TcpClient(host, port, timeout);
    }

    public Object run(TcpClientService service){
        Object result = null;
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(serverHost, serverPort), timeout);
            log.debug("成功连接服务端：{} : {}", serverHost, serverPort);

            result = service.handel(socket);
        } catch (IOException e) {
            log.error("客户端异常：", e);
        } finally {
            if(socket != null){
                try {
                    log.debug("关闭socket");
                    socket.close();
                } catch (IOException e) {
                    log.error("客户端关闭Socket异常：", e);
                }
            }
        }
        log.debug("客户端退出");
        return result;
    }
}
